package com.dns.reset.exec;

import com.dns.reset.core.SshUtil;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.*;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

public class CmdExecutor {
	
	private static final Logger logger = LoggerFactory.getLogger(CmdExecutor.class);
	
	private static ListeningExecutorService pool;
	
	private static List<ListenableFuture<String>> futures;

	private static boolean sequence=false;


	public  static void execute(SshUtil ssh, String cmd){
		Validate.notNull(ssh,"ssh清单不能为空！");
		pool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
		futures = Lists.newArrayList();
				ListenableFuture<String> future = pool.submit(new Callable<String>() {
					@Override
					public String call() throws Exception {
						return exec(cmd, ssh);
					}
				});
				futures.add(future);
		execFutures(futures);
	}
	
	private static String exec(String cmd, SshUtil ssh){
		try {
			return ssh.exec(cmd).result();

		} catch (Exception e) {
			logger.error("主机:"+ssh.ip()+"命令执行失败!",e);
		}
		return "failure";
	}

	/**
	 * 执行futures
	 * @param futures
	 * @author gulixing@msn.com
	 * @date   2016年8月1日
	 */
	private static void execFutures(List<ListenableFuture<String>> futures) {
		//命令按顺序返回结果
		if(sequence){
			ListenableFuture<List<String>> successfulQueries = Futures.successfulAsList(futures);
			Futures.addCallback(successfulQueries, new FutureCallback<List<String>>() {
				  @Override
				  public void onSuccess(List<String> results) {
					  for (String result : results) {
					      System.out.println(result);					
					  }
				  }

				  @Override
				  public void onFailure(Throwable t) {
				      logger.error("执行失败",t);
				  }
		    });
		}
		else{
			for (ListenableFuture<String> future : futures) {
				Futures.addCallback(future, new FutureCallback<String>(){
					  @Override
					  public void onSuccess(String  result) {

					  	logger.info("执行结果：{}",result);
					  }
	
					  @Override
					  public void onFailure(Throwable t) {
					      logger.error("执行失败",t);
					  }
				});
			}
		}
	}

	

		

}